# !/usr/bin/env python
# -*- coding: utf-8 -*-
# 2019/03/16
# 淘宝秒杀脚本，扫码登录版
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC
import datetime
import time
from splinter.browser import Browser

from common import DoConfig
import sys
import os

config_path = sys.path[1] + os.sep + 'common' + os.sep + 'config.ini'


def login_jd():
    try:
        # 打开淘宝登录页，并进行扫码登录
        # browser.get("https://item.jd.com/100012043978.html")
        browser.get("https://item.jd.com/28065667823.html")

        time.sleep(1)
        if browser.find_element_by_link_text("你好，请登录"):
            browser.find_element_by_link_text("你好，请登录").click()
            print("请在15秒内完成扫码")
            time.sleep(10)
        # 购物数量增加2
        # browser.find_element_by_xpath('/html/body/div[6]/div/div[2]/div[4]/div[17]/div/div/a[2]').click()
        browser.find_element_by_xpath('//*[@id="choose-btns"]/div/div/a[2]').click()
        now = datetime.datetime.now()
        print('login success:', now.strftime('%Y-%m-%d %H:%M:%S'))
        # 判断当前时间是否满足要求，即加入购物车按钮是否可用
        now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.ID, 'InitCartUrl')))
        # 到货通知
        displayed = browser.find_element_by_id('btn-notify').is_displayed()
        while displayed:
            print('还未到时间，刷新当前页面')
            browser.refresh()
            displayed = browser.find_element_by_id('btn-notify').is_displayed()
        browser.find_element_by_link_text("加入购物车").click()
        # browser.get('https://cart.jd.com/cart_index/')
        # 点击加入购物车 判断是否可以点击 去购物车结算
        WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[5]/div[1]/div/div/div/div[2]/div[3]/a[2]')))
        browser.find_element_by_link_text("去购物车结算").click()
        # print(2222222)
        # 判断是否加载完成
        WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="cart-body"]/div[1]/div[5]/div/div[2]/div/div/div/div[2]/div[2]/div/div[1]/a')))
        # 全选
        # browser.find_element_by_xpath('/html/body/div[5]/div[1]/div[3]/div[1]/div/input')
        # 结算
        browser.find_element_by_xpath('//*[@id="cart-body"]/div[1]/div[5]/div/div[2]/div/div/div/div[2]/div[2]/div/div[1]/a').click()
        # 提交订单
        WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.ID, 'order-submit')))
        browser.find_element_by_id("order-submit").click()
        # 打开支付页面，60秒内支付
        time.sleep(60)
        print(11111)
    except selenium.common.exceptions.NoSuchElementException as e:
        print(e)
    finally:
        browser.quit()


def login_tianmao():
    # 打开淘宝登录页，并进行扫码登录
    browser.get("https://www.tmall.com/")
    time.sleep(3)
    if browser.find_element_by_link_text("请登录"):
        browser.find_element_by_link_text("请登录").click()
        print("请在15秒内完成扫码")
        time.sleep(15)
        # 打开购物车
        browser.get("https://cart.taobao.com/cart.htm")
    # time.sleep(3)
    now = datetime.datetime.now()
    print('login success:', now.strftime('%Y-%m-%d %H:%M:%S'))


def buy(times, choose):
    # 点击购物车里全选按钮
    # if choose == 2:
    #     print("请手动勾选需要购买的商品")
    while True:
        now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        # 对比时间，时间到的话就点击结算
        if now > times:
            if choose == 1:
                while True:
                    try:
                        if browser.find_element_by_id("J_SelectAll2"):
                            browser.find_element_by_id("J_SelectAll2").click()
                            break
                    except:
                        print("找不到购买按钮")
            # 点击结算按钮
            while True:
                try:
                    if browser.find_element_by_link_text("结 算"):
                        browser.find_element_by_link_text("结 算").click()
                        print("结算成功")
                        break
                except:
                    pass
            while True:
                try:
                    if browser.find_element_by_link_text('提交订单'):
                        browser.find_element_by_link_text('提交订单').click()
                        now1 = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
                        print("抢购成功时间：%s" % now1)
                except:
                    print("再次尝试提交订单")
            # time.sleep(0.01)


def login_taobao():
    login_url = 'https://login.taobao.com/member/login.jhtml?redirectURL=http%3A%2F%2Fcart.taobao.com%2Fcart.htm'
    browser.get(login_url)
    time.sleep(5)
    login_ele = browser.find_element_by_id('fm-login-id')
    login_ele.click()
    login_ele.send_keys('18502041807')


if __name__ == "__main__":
    config = DoConfig.DoConfig(config_path)
    pathInfo_dict = config.get_dict('pathInfo')
    driver_path = pathInfo_dict.get('executable_path')

    today = datetime.datetime.now().strftime('%Y-%m-%d')
    times_jd = today + ' 10:00:00.000000'
    times_tianmao = today + ' 20:00:00.000000'
    # i = int(input('请输入抢购来源，1 天猫，2 京东'))
    # print(times_jd)
    i = 2
    # print(times_tianmao)
    # 时间格式："2018-09-06 11:20:00.000000"
    browser = webdriver.Chrome(driver_path)
    browser.maximize_window()
    # '''

    if i == 1:
        login_tianmao()
        # choose = int(input("到时间自动勾选购物车请输入“1”，否则输入“2”："))
        choose = 1
        buy(times_tianmao, choose)
    elif i == 2:
        login_jd()
# '''
